import IBreadCrumb from '@/layouts/components/IBreadCrumb.tsx';
import { Outlet, useLocation } from 'react-router-dom';
import LayoutWrapper from '@/layouts/LayoutWrapper.tsx';
import { useEffect, useMemo, useRef } from 'react';
import { useEvent } from 'react-use';
import { debounce } from 'lodash-es';
import { useRefreshUserInfo, useUserToken } from '@/store/userStore.ts';
import { useQuery } from '@tanstack/react-query';

const ILayout = () => {
  const mainContent = useRef<HTMLDivElement>(null);

  const calcHeight = () => {
    const clientHeight = document.body.clientHeight;
    if (mainContent.current) {
      mainContent.current.style.maxHeight = `${clientHeight - 80 - 61 - 5}px`;
    }
  };
  const location = useLocation();
  const token = useUserToken();
  const refreshUserInfo = useRefreshUserInfo();

  useQuery({
    queryKey: ['userInfo', token],
    queryFn: refreshUserInfo,
    enabled: !!token,
  });

  const isMainLayout = useMemo<boolean>(() => {
    return !(
      location.pathname.startsWith('/real-time-monitoring') ||
      location.pathname.startsWith('/history-replay')
    );
  }, [location.pathname]);

  useEvent('resize', debounce(calcHeight, 100));

  useEffect(() => {
    if (isMainLayout) calcHeight();
  }, [isMainLayout]);

  return (
    <>
      <LayoutWrapper>
        {isMainLayout ? (
          <>
            <IBreadCrumb />
            <div ref={mainContent} className="main-content h-full overflow-auto px-10 py-6">
              <Outlet />
            </div>
          </>
        ) : (
          <>
            <div className="main-content h-full overflow-auto">
              <Outlet />
            </div>
          </>
        )}
      </LayoutWrapper>
    </>
  );
};

export default ILayout;
